//
//  ViewController1.swift
//  SWIFTLEARN
//
//  Created by chichaojituan521 on 2017/5/12.
//  Copyright © 2017年 linch. All rights reserved.
//


import UIKit
//MARK: -字符串索引
extension String {
    
    subscript (start:Int,length:Int) ->String
    {
        get{
            let index1 = self.index(self.startIndex,offsetBy:start)
            let index2 = self.index(index1, offsetBy: length)
            let range = Range(uncheckedBounds: (lower: index1, upper: index2))
            return self.substring(with: range)
            
        }
        set{
            let tmp = self
            var s = ""
            var e = ""
            
            for (index,item) in tmp.characters.enumerated()
            {
                if index < start
                {
                    s += "\(item)"
                }
                if index > start + length
                {
                    e += "\(item)"
                }
                self = s + newValue + e
            }
        }
    }
    subscript (index:Int) ->String
    {
        get{
            return String(self[self.index(self.startIndex, offsetBy: index)])
        }
        set{
            let tmp = self
            self = ""
            for (idx, item) in tmp.characters.enumerated()
            {
                if idx == index {
                    self += "\(newValue)"
                }else{
                    self += "\(item)"
                }
            }
        }
        
    }
    
}

protocol Animal{
    func move()
}

class ViewController1: UIViewController,UITextFieldDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.orange
        
        let btnName:[String] = ["字符随机数","数组字典结构体枚举","循环","字符串截取","计算属性","自己实现二维数组","字符串索引","协议","文件操作","UIlabel","UIButtonUISwith","UITextField UITextView"]
        
        let btnInterval: Int = 10
        
        let btnWidth = (self.view.frame.size.width - CGFloat(btnInterval) * 5)/4.0
        
        
        for btnitem in 1...12 {
            
            let item = btnitem - 1
            
            let button = UIButton(type: .custom)
            button.tag = btnitem
            
            self.view.addSubview(button)
            
            button.setTitle(btnName[item], for: .normal)
            button.titleLabel!.font = UIFont.systemFont(ofSize: 13)
            button.titleLabel!.lineBreakMode = .byWordWrapping
            button.backgroundColor = UIColor.lightGray
            
            let btncgx = btnInterval + (Int(item) % 4) * (Int(btnWidth) + btnInterval)
            let btncgy = 74 + (Int(item) / 4) * (btnInterval + 50)
            button.frame = CGRect(x:btncgx , y:btncgy , width: Int(btnWidth), height: 50)
            
            button.addTarget(self, action: #selector(buttonClickMethod(_:)),for: .touchUpInside)
            
        }
        

        
        
              // Do any additional setup after loading the view.
    }
    
    func buttonClickMethod(_ button:UIButton) {
        
        switch button.tag {
        case 1:
            self.numberTest()
        case 2:
            self.arrayDictStruct()
        case 3:
            self.controlCollection()
        case 4:
            self.cutwordsFromWords()
        case 5:
            self.jiSuanShuXing()
        case 6:
            self.twoDimensionArray()
        case 7:
            self.charactorIndex()
        case 8:
            self.protocolLearnDemo()
        case 9:
            self.documentHandlerMethod()
        case 10:
            self.createUIlabelMethod()
        case 11:
            self.createUIbuttonMethod()
        case 12:
            self.createUItextFieldMethod()
            
        default:
            print("case===")
        }
    }

    

    //MARK:- 二维数组
    class TDArray{
        let rows: Int, columns: Int
        var array = [String]()
        
        init(rows:Int,columns:Int) {
            self.rows = rows
            self.columns = columns
            self.array = Array(repeating: "default", count: rows * columns)
            
        }
        func indexIsValidForRow(row: Int, column: Int) -> Bool {
            return row >= 0 && row < rows && column >= 0 && column < columns
        }
        subscript(row:Int,column:Int) ->String{
            get{
                assert(self.indexIsValidForRow(row: row, column: column), "越界了")
                return self.array[(row-1)*rows + column]
            }
            set{
                assert(self.indexIsValidForRow(row: row, column: column), "越界了")
                self.array[((row - 1) * rows) + column] = newValue
            }
        }
        
    }
    
    
    class People
    {
        //普通属性
        var firstName:String = ""
        var lastName:String  = ""
        var nickName:String  = ""
        
        //计算属性
        var fullName:String
        {
            get
            {
                return nickName + " " + firstName + " " + lastName
            }
            
        }
        
        //带属性监视器的普通属性
        var age:Int = 0
        {
            //我们需要在age属性变化前做点什么
            willSet
            {
                print("Will set an new value \(newValue) to age")
            }
            //我们需要在age属性发生变化后，更新一下nickName这个属性
            didSet
            {
                print("age  changed form \(oldValue) to \(age)")
                if age<10
                {
                    nickName = "Little"
                }else
                {
                    nickName = "Big"
                }
            }
        }
        func toString() -> String
        {
            return "Full Name: \(fullName) " + ", Age: \(age) "
        }
    }
    class Calcuator {
        var a:Int = 1
        var b:Int = 1
        var sun:Int{
            get{
                return a + b
            }
            set{
                a = newValue - b
            }
        }
    }
    class Bird: Animal {
        func move() {
            print("jumpAndJump")
        }
        
        func songASong(name:String) -> String {
            return "唱的歌是\(name)"
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.dismiss(animated: true) { 
            
        }
    }
    
    //MARK:- 字符串
    
    func numberTest()
    {
        let str: String = "hangge.com"
        let number: Int = 32
        
        if str.hasPrefix("han") {
            print("yes   have")
        }
        if str.hasSuffix(".com")
        {
            print("yes   have too")
        }
        print("---------\(str.count)")
        
        
        let msg = "student number is \(number)"
        
        print(msg)
        
        let yuanzu = (one:"ooo",two:"ttt")
        
        print(yuanzu.one)
        
        let temp = Int(arc4random()%100)+1
        let temp1 = Int(arc4random_uniform(100))+1
        print("++++\(temp)++++++\(temp1)")
        
        for _ in 11...111 {
            let temp = Int(arc4random()%100)+1
            let temp1 = Int(arc4random_uniform(100))+1
            print("++++\(temp)++++++\(temp1)")
        }
        for icount in (11..<111).reversed(){
            
            print("=====\(icount)")
            
        }
        
        let words = "语言是苹果公司在2014年的上发布的全新的编程语言"
        
        let index = words.index(words.startIndex, offsetBy: 4)
        
        print("====\(index)")
        
        let wordsO = words.substring(from: index)
        let wordsT = words.substring(to: index)
        
        
        print(wordsO)
        print(wordsT)
        
        
        struct CenterPointer{
            var x=0, y=0
        }
        
        func reloadstruct (left:CenterPointer, right:CenterPointer) -> CenterPointer{
            return CenterPointer(x:(left.x+right.x)/2, y:(left.y+right.y)/2)
        }
        
        let point1 = CenterPointer(x:2,y:3)
        let point2 = CenterPointer(x:4,y:5)
        
        let point3 = reloadstruct(left: point1, right: point2)
        
        print(point3)
    }
    //MARK:- 数组，字典，结构体，枚举
    func arrayDictStruct()  {
        
        //数组
        let menbers = ["pig","cat","bird"]
        
        var zoo = [String]()
        
        //添加元素
        zoo.append("dog")
        zoo += ["lion"]
        zoo.insert("mouse", at: 0)
        zoo[1] = "pig000"
        
        print(zoo)
        
        zoo[0...2] = ["message","hangge","com"]
        
        
        print(zoo)
        
        let arrcout = zoo.count
        if zoo.isEmpty {
            
        }
        else
        {
            print(arrcout)
        }
        var arrBig = menbers + zoo
        
        print(arrBig)
        arrBig.remove(at: 2)
        arrBig.removeLast()
        arrBig.removeAll()
        print(arrBig)
        
        
        //字典
        var empty = [String:Int]()
        
        var myDic = ["name":"hangge",
                     "url":"hangge.com"]
        
        myDic["address"] = "china"
        myDic["age"] = "23"
        myDic.removeValue(forKey: "name")
        //遍历
        for (key,value) in myDic {
            print("\(key):\(value)");
        }
        
        //只遍历字典的键（key）
        for key in myDic.keys {
            print("\(key)");
        }
        
        //只遍历字典的值（value）
        for value in myDic.values {
            print("\(value)");
        }
        
        //结构体
        
        struct BookInfo{
            var ID:Int = 0
            var Name:String = "Defaut"
            var Author:String = "Defaut"
        }
        
        
        var book2 = BookInfo(ID:0021,Name:"航歌",Author:"hangge")
        book2.ID = 12
        
        print(book2)
        enum weekday{
            
            case monday
            case tuesday
            case wednesday
            case thursday
            case friday
            case saturday
            case sunday
            
        }
        
        
        var dayday = weekday.monday
        
        var day21:weekday = .wednesday
        
        
        
    }
    //MARK:-- 控制流
    func controlCollection() {
        
        let fruit = "pig-"
        switch fruit {
        case "eye":
            print("eye")
        case "pig":
            print("pig")
        case "dog":
            print("dog")
        case "ttttt":
            print("tttt")
        default:
            print("ooooo-----")
            
        }
        let age = 5
        switch age {
        case 0...11:
            print("正太")
        case 12...30:
            print("少年")
        default:
            print("大叔")
        }
        
        let height = 1.72
        switch height{
        case 1...3 where height == 1.72:
            print("case 1")
        case 1...3 where height == 2:
            print("case 2")
        default:
            print("default")
        }
        
        for i in 1..<100{
            print("\(i)")
        }
        
        //遍历数组元素
        let numbers = [1,2,4,7]
        for num in numbers{
            print("\(num)")
        }
        
        //遍历字典
        let nameOfAge = ["lily":18, "Candy":24]
        for (aName, iAge) in nameOfAge{
            print("\(aName) is \(iAge)")
        }
        
        //遍历字符串的字符
        for chare in "hangge" {
            print(chare)
        }
        
        //循环
        (1...10).forEach {
            print($0)
        }
        "hangge".forEach {
            
            print($0)
            
        }
        
        var i = 2
        
        while i<100 {
            i += 1
            print("===\(i)")
        }
        
        repeat{
            i += 1
            print("+++++\(i)")
        }while i<200
    }
    
    //MARK:- 字符串截取
    func cutwordsFromWords()  {
        let strS = "Disposeofanresonbeecreated."
        let index1 = strS.index(strS.startIndex, offsetBy: 6)
        let index2 = strS.index(index1, offsetBy: 4)
        let range = Range(uncheckedBounds: (lower:index1,upper:index2))
        let  strss = strS.substring(with: range)
        let ssssU = strS[index1]
        let str111 = strS.substring(from: index1);
        let str222 = strS.substring(to: index1);
        print(strss)
        print(str111)
        print(str222)
        print("+++++++++\(ssssU)")
    }
    //MARK: - 计算属性
    func jiSuanShuXing() {
        let lily = People()
        lily.age = 34
        lily.firstName = "l"
        
        print ("+++++\(lily.nickName)")
        
        let cal = Calcuator()
        
        print(cal.sun)
        cal.sun = 7
        
        print(cal.b)
        
        
    }
    //MARK:-二维数组
    func twoDimensionArray() {
        
        let  arrayMe = TDArray(rows: 20, columns: 20)
        arrayMe[12,16] = "wqvb"
        print("======\(arrayMe[12,19])")
        print("======\(arrayMe[12,16])")
        
        
    }
    func charactorIndex () {
        var str = "hangge.com"
        print(str[7,3])
        print(str[7])
        
        str[7,3] = "COM"
        str[0] = "H"
        
        print(str[0,10])
    }
    
    //MARK: - 协议
    func protocolLearnDemo()
    {
        let bird = Bird()
        bird.move()
        print("--------\(bird.songASong(name: "TELL ME WHY "))")
        
    }
    //文件操作
    func documentHandlerMethod()  {
        let manager = FileManager.default
        let urlDoc = manager.urls(for: .documentDirectory, in: .userDomainMask)
        let url = urlDoc[0]
        //nsurl 类型路径
        let demoUrl1 = url.appendingPathComponent("test.txt")
        
        //  string  类型路径
        let demoUrl2 = NSHomeDirectory() + "Doctments/test.txt"
        
        print(demoUrl1)
        
        print(demoUrl2)
        

        
        //        对指定路径执行浅搜索，返回指定目录路径下的文件、子目录及符号链接的列表
        //无路径,不会对子文件夹遍历
        let contentsOfPath = try? manager.contentsOfDirectory(atPath: url.path)
        print("contentsOfPath: \(String(describing: contentsOfPath))")
        
        //        有路径,不会对子文件夹遍历
        let content2 = try?manager.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options:.skipsHiddenFiles)
        print("content2:\(String(describing: content2))")
        
        
        //        深度遍历，会递归遍历子文件夹//只有文件层次 和文件名字  .无路径
        let content3 = manager.enumerator(atPath:url.path)
        print("content3:\(String(describing: content3?.allObjects))")
        //        有路径,有子文件的路径
        let content4 = manager.enumerator(at: url, includingPropertiesForKeys: nil, options: .skipsHiddenFiles, errorHandler: nil)
        print("--------\(String(describing: content4?.allObjects))")
        //无路径,会遍历子文件
        let subPaths = manager.subpaths(atPath: url.path)
        print("++++++++++++subPaths: \(String(describing: subPaths))")
        
        
        //        判断文件或文件夹是否存在
        let fileManager = FileManager.default
        let filePath:String = NSHomeDirectory() + "/Documents/icon.png"
        let exist = fileManager.fileExists(atPath: filePath)
        print(exist)
        print("=======:\(NSHomeDirectory())")
        
        
        //创建文件夹
        let myDocumentDir :String = NSHomeDirectory() + "/Documents/LINCHS/linchs"
        try!fileManager.createDirectory(atPath: myDocumentDir, withIntermediateDirectories: true, attributes: nil)
        
        
        //        1）把String保存到文件
        let strFilePath:String = NSHomeDirectory() + "/Documents/hangge.txt"
        let info = "欢迎来到hange.com"
        try! info.write(toFile: strFilePath, atomically: true, encoding: String.Encoding.utf8)
        
        //        2）把图片保存到文件路径下
        let imgPath = NSHomeDirectory() + "/Documents/LINCHS/linchs/hangge.png"
        let image = UIImage(named: "天天购.jpg")
        let dataImg :Data! = UIImagePNGRepresentation(image!)
        try? dataImg.write(to: URL(fileURLWithPath: imgPath))
        
        //        3）把NSArray保存到文件路径下
        
        
        let array = NSArray(objects: "aaa","bbb","ccc")
        
        let arrayFilePath:String = NSHomeDirectory() + "/Documents/array.plist"
        array.write(toFile: arrayFilePath, atomically: true)
        
        
        let arrayOne:[String] = ["aaa","bbb","ccc"]
        
        let arrayOnePath = NSHomeDirectory() + "/Documents/LINCHS/linchs/array.plist"
        
        let nsArrayOne:NSArray = arrayOne as NSArray
        
        nsArrayOne.write(toFile: arrayOnePath, atomically: true)
        
        
        
        //        4）把NSDictionary保存到文件路径下
        
        let dictionary:NSDictionary = ["Gold": "1st Place", "Silver": "2nd Place"]
        let dictPath:String = NSHomeDirectory() + "/Documents/dictionary.plist"
        dictionary.write(toFile: dictPath, atomically: true)
        
        //        在文档目录下新建test.txt文件
        
        let createDoc = NSHomeDirectory() + "/Documents/LINCHS/linchs/你好.txt"
        let isExit = fileManager.fileExists(atPath: createDoc)
        
        if !isExit {
            let str = "wqvb"
            let data = Data(base64Encoded: str)
            
            let createRes = fileManager.createFile(atPath: createDoc, contents: data, attributes: nil)
            print("文件创建结果: \(createRes)")
        }
        
        //        复制文件  copyItem
        
        
        let srcUrl = NSHomeDirectory() + "/Documents/hangge.txt"
        let toUrl = NSHomeDirectory() + "/Documents/copyed.txt"
        if  !fileManager.fileExists(atPath: toUrl) {
            try! fileManager.copyItem(atPath: srcUrl, toPath: toUrl)
            
        }
        
        
        //        移动文件
        //方法1
        let onePath = NSHomeDirectory() + "/Documents/hangge.txt"
        let twoPath = NSHomeDirectory() + "/Documents/LINCHS/hanggggggg.txt"
        try? fileManager.moveItem(atPath: onePath, toPath: twoPath)
        //方法2
        let threePath = url.appendingPathComponent("copyed.txt")
        let fourPath = url.appendingPathComponent("LINCHS/coooo.txt")
        try?fileManager.moveItem(at: threePath, to: fourPath)
        
        
        //删除文件
        try?fileManager.removeItem(atPath: twoPath)
        
        //      删除目录下所有的文件
        let urlOld = NSHomeDirectory() + "/Documents/docs"
        let urlNew = NSHomeDirectory() + "/Documents/LINCHS/docssdocss"
        
        if fileManager.fileExists(atPath: urlNew)
        {
            try?fileManager.removeItem(atPath: urlNew)
        }
        
        try?fileManager.copyItem(atPath: urlOld, toPath: urlNew)
        
        let  fileArray = fileManager.subpaths(atPath: urlNew)
        
        for fn in fileArray!{
            try! fileManager.removeItem(atPath: urlNew + "/\(fn)")
        }
        
        
    }
    
    //MARK: - UI
    
    func createUIlabelMethod() {
        let label = UILabel(frame:CGRect(x:10, y:380, width:300, height:50))
        label.text = "hangge.com.backgroundColor"
        label.backgroundColor = UIColor.red
        self.view.addSubview(label);
        label.textAlignment = .center
        //文字的阴影
        label.shadowColor = UIColor.orange
        label.shadowOffset = CGSize(width: 5, height: 15)
        
        
        
        label.layer.shadowColor = UIColor.green.cgColor
        label.layer.shadowOffset = CGSize(width: 12, height: 12)
        
        label.font = UIFont(name: "Zapfino", size: 50)
        label.font = UIFont.boldSystemFont(ofSize: 30)
        
        
        label.lineBreakMode = .byTruncatingTail  //隐藏尾部并显示省略号
        label.lineBreakMode = .byTruncatingMiddle  //隐藏中间部分并显示省略号
        label.lineBreakMode = .byTruncatingHead  //隐藏头部并显示省略号
        label.lineBreakMode = .byClipping  //截去多余部分也不显示省略号
        
        //        label.adjustsFontSizeToFitWidth = true
        label.numberOfLines = 3
        
        
        //设置文本高亮
        label.isHighlighted = true
        //设置文本高亮颜色
        label.highlightedTextColor = UIColor.gray
        
        
        //富文本设置
        let attributeString = NSMutableAttributedString(string:"welcome to hangge.com")
        //从文本0开始6个字符字体HelveticaNeue-Bold,16号
        attributeString.addAttribute(NSFontAttributeName,
                                     value: UIFont(name: "HelveticaNeue-Bold", size: 16)!,
                                     range: NSMakeRange(0,6))
        //设置字体颜色
        attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue,
                                     range: NSMakeRange(0, 3))
        //设置文字背景颜色
        attributeString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.green,
                                     range: NSMakeRange(3,3))
        label.attributedText = attributeString
        
    }
    func createUIbuttonMethod() {
        let button1 = UIButton(type: .custom)
        button1.frame = CGRect(x: 10, y: 440, width: 60, height: 40)
        button1.backgroundColor = UIColor.yellow
        button1.setTitle("button1", for: .normal)
        self.view.addSubview(button1)
        button1.addTarget(self, action: #selector(tapButton1), for: .touchUpInside)
        button1.setTitleColor(UIColor.black, for: .normal) //普通状态下文字的颜色
        button1.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        
        let btnIcon = UIImage(named: "btnbtn")?.withRenderingMode(.alwaysOriginal)
        let button2 = UIButton(type: .custom)
        button2.frame = CGRect(x: 100, y: 440, width: 60, height: 40)
        button2.setImage(btnIcon, for: .normal)
        self.view.addSubview(button2)
        button2.addTarget(self, action: #selector(tapButton2(_ :)), for: .touchUpInside)
        button2.adjustsImageWhenHighlighted = true
        button2.adjustsImageWhenDisabled = true
        button2.layer.cornerRadius = 5
        button2.clipsToBounds = true
        
        
        
        let uiswitch = UISwitch()
        //设置位置（开关大小无法设置）
        uiswitch.center = CGPoint(x:100, y:350)
        //设置默认值
        uiswitch.isOn = true;
        uiswitch.addTarget(self, action: #selector(switchDidChange(_:)), for:.valueChanged)
        self.view.addSubview(uiswitch);
        
        
        
        
    }
    func switchDidChange(_ swith:UISwitch){
        //打印当前值
        print(swith.isOn)
    }
    func tapButton1() {
        print("tap button1")
        let vc2 = ViewController2()
        self.navigationController?.pushViewController(vc2, animated: true)
        
    }
    func tapButton2(_ btn:UIButton) {
        print("tap button2")
        
    }

    func createUItextFieldMethod(){
        
        let textField = UITextField(frame: CGRect(x:10, y:240, width:200, height:30))
        
        textField.borderStyle = .line
        self.view.addSubview(textField)
        textField.delegate = self
        textField.placeholder = "请输入用户名"
        textField.minimumFontSize = 11
        
        //        背景图片设置
        //        textField.borderStyle = .none //先要去除边框样式
        //        textField.background = UIImage(named:"background1");
        
//        textField.clearButtonMode = .whileEditing  //编辑时出现清除按钮
//        textField.clearButtonMode = .unlessEditing  //编辑时不出现，编辑后才出现清除按钮
        textField.clearButtonMode = .always  //一直显示清除按钮
        /*
         
         设置文本框关联的键盘类型
         Default：系统默认的虚拟键盘
         ASCII Capable：显示英文字母的虚拟键盘
         Numbers and Punctuation：显示数字和标点的虚拟键盘
         URL：显示便于输入url网址的虚拟键盘
         Number Pad：显示便于输入数字的虚拟键盘
         Phone Pad：显示便于拨号呼叫的虚拟键盘
         Name Phone Pad：显示便于聊天拨号的虚拟键盘
         Email Address：显示便于输入Email的虚拟键盘
         Decimal Pad：显示用于输入数字和小数点的虚拟键盘
         Twitter：显示方便些Twitter的虚拟键盘
         Web Search：显示便于在网页上书写的虚拟键盘
         
         */
        textField.keyboardType = UIKeyboardType.default
        
        textField.becomeFirstResponder()
        textField.resignFirstResponder()
        
        textField.returnKeyType = UIReturnKeyType.google
        //        textField.returnKeyType = UIReturnKeyType.done //表示完成输入
        //        textField.returnKeyType = UIReturnKeyType.go //表示完成输入，同时会跳到另一页
        //        textField.returnKeyType = UIReturnKeyType.search //表示搜索
        //        textField.returnKeyType = UIReturnKeyType.join //表示注册用户或添加数据
        //        textField.returnKeyType = UIReturnKeyType.next //表示继续下一步
        //        textField.returnKeyType = UIReturnKeyType.send //表示发送
        
        
        
        let textView = UITextView(frame: CGRect(x: 50, y: 300, width: 200, height: 200))
        
        textView.layer.borderWidth = 1  //边框粗细
        textView.layer.borderColor = UIColor.gray.cgColor //边框颜色
        self.view.addSubview(textView)
        textView.isEditable = true
        textView.isSelectable = true
        
        textView.dataDetectorTypes = [] //都不加链接
        textView.dataDetectorTypes = UIDataDetectorTypes.phoneNumber //只有电话加链接
        textView.dataDetectorTypes = UIDataDetectorTypes.link //只有网址加链接
        textView.dataDetectorTypes = UIDataDetectorTypes.all //电话和网址都加
        
        
        let mail = UIMenuItem(title: "邮件", action: #selector(clickonMail))
        let weixin = UIMenuItem(title: "微信", action: #selector(clickonWeiXin))
        let menu = UIMenuController()
        menu.menuItems = [mail,weixin]
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        print(textField.text as Any)
        return true
    }
    func clickonMail() {
        print("邮件")
    }
    func clickonWeiXin() {
        print("微信")
    }

    
}
